import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.List;

import javax.swing.JOptionPane;
import javax.swing.SwingWorker;

public class Client extends SwingWorker<Void, Integer> {
        
	private final static int port = 1234;
	private final static int sizeOfBuffer = 65536;
	public static Socket server;
	public File file;
	
	public Client(File file) { 
		this.file=file; 
	}

	@Override
	public Void doInBackground() throws Exception {
		Send(file);
		return null;
	}

	@Override
	public void process(List<Integer> percents) {
		for (int number : percents) {
			GUI.progressBar.setValue(number);
		}
	}
	

	public void Send(File file) {
		try{
			server = new Socket("localhost", port);
			FileInputStream in = new FileInputStream(file);
			DataOutputStream out = new DataOutputStream(server.getOutputStream());
			out.writeUTF(file.getName());
			out.writeLong(file.length());

			byte[] buffer = new byte[sizeOfBuffer];
			int count;
			long total = file.length();

			while (total > 0) {
				count = in.read(buffer);
				total -= count;
				out.write(buffer, 0, count);
				publish((int) ((file.length()-total)/file.length()*100));
			}
			out.flush();

			in.close();
			JOptionPane.showMessageDialog(GUI.frame, "File was successfully sent","Message",JOptionPane.INFORMATION_MESSAGE);
			
		} catch(IOException e) {
			JOptionPane.showMessageDialog(GUI.frame, "No connection to server","Message",JOptionPane.INFORMATION_MESSAGE);
			e.printStackTrace();
		} finally {
			try{
				server.close();
			} catch (IOException e) {
				System.out.println(e.toString());
			}
		}
	}
}